package br.unicamp.ic.lis.dbvapi.domain;

import java.io.Serializable;

import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.MapsId;
import javax.persistence.Table;

@Entity
@Table(name = "LogicalVersion")
public class LogicalVersion implements Serializable, Comparable<LogicalVersion> {

	private static final long serialVersionUID = -7324963560634398110L;

	@EmbeddedId
	private LogicalVersionPK logicalVersionPK;

	@MapsId("oid")
	@ManyToOne
	private MultiversionObject multiversionObject;

	@MapsId("dbvid")
	@ManyToOne
	private DBV dbv;

	@ManyToOne
	private AbstractPhysicalVersion<?> physicalVersion;

	public LogicalVersion() {

	}

	public LogicalVersion(MultiversionObject multiversionObject, DBV dbv,
			AbstractPhysicalVersion<?> physicalVersion) {
		this.multiversionObject = multiversionObject;
		this.dbv = dbv;
		this.physicalVersion = physicalVersion;
		logicalVersionPK = new LogicalVersionPK(multiversionObject, dbv);
	}

	public LogicalVersionPK getLogicalVersionPK() {
		return logicalVersionPK;
	}

	public void setLogicalVersionPK(LogicalVersionPK logicalVersionPK) {
		this.logicalVersionPK = logicalVersionPK;
	}

	public AbstractPhysicalVersion<?> getPhysicalVersion() {
		return physicalVersion;
	}

	public void setPhysicalVersion(AbstractPhysicalVersion<?> physicalVersion) {
		this.physicalVersion = physicalVersion;
	}

	public MultiversionObject getMultiversionObject() {
		return multiversionObject;
	}

	public void setMultiversionObject(MultiversionObject multiversionObject) {
		this.multiversionObject = multiversionObject;
	}

	public DBV getDbv() {
		return dbv;
	}

	public void setDbv(DBV dbv) {
		this.dbv = dbv;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime
				* result
				+ ((logicalVersionPK == null) ? 0 : logicalVersionPK.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		LogicalVersion other = (LogicalVersion) obj;
		if (logicalVersionPK == null) {
			if (other.logicalVersionPK != null)
				return false;
		} else if (!logicalVersionPK.equals(other.logicalVersionPK))
			return false;
		return true;
	}

	@Override
	public String toString() {
		Long pvid = null;
		if (this.getPhysicalVersion() != null) {
			pvid = this.getPhysicalVersion().getId();
		}

		String dbv = this.getDbv().getStamp() + "_"
				+ this.getDbv().getScale().getValue();

		return "LogicalVersion [o=" + logicalVersionPK.getOid() + ", d=" + dbv
				+ ", pv=" + pvid + "]";
	}

	@Override
	public int compareTo(LogicalVersion other) {
		return this.getMultiversionObject().compareTo(
				other.getMultiversionObject());
	}

}
